package com.xplay.xpocker.room.mahjong.event;

import com.xplay.xpocker.room.message.MessageContent;
import com.xplay.xpocker.room.message.service.ActionMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
public class UserActionListener {

    @Autowired
    private ActionMessageService actionMessageService;

    @Autowired
    private TaskExecutor taskExecutor;

    /**
     * 如果这个函数没有增加 @Async  是不支持 事务提交后 执行的
     * <p>
     * 当当前用户拿到的数据和其他用户拿到的数据 不一样的时候 这里 是不是繁琐了一点
     *
     * @param event
     */
    @Async
    @TransactionalEventListener(classes = UserEvent.class, fallbackExecution = true, phase = TransactionPhase.AFTER_COMMIT)
    public void notifyAll(UserEvent event) {
        MessageContent<Object> message = event.getData();
        taskExecutor.execute(() -> {
            try {
                Thread.sleep(event.getSleepTime());
                actionMessageService.doMessage(message.getRoomCode(), message);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

    }
}
